package com.wsdcd.zlg.sb.model.service.impl;

import com.wsdcd.zlg.sb.mapper.StatisticsMapper;
import com.wsdcd.zlg.sb.model.entity.Statistics;
import com.wsdcd.zlg.sb.model.service.StatisticsService;
import com.wsdcd.zlg.sb.util.AboutTime;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@AllArgsConstructor
@Service
public class StatisticsServiceImpl implements StatisticsService {
	private final StatisticsMapper statisticsMapper;
	
	@Override
	public String getWeekData(){		
		StringBuilder str = new StringBuilder();
		List<Statistics> list = statisticsMapper.selectAll();
		for (Statistics statistic : list) {
			str.append(statistic.getOrderNumber()).append(",");
		}
		str = new StringBuilder(str.substring(0, str.lastIndexOf(",")));
		return str.toString();
	}
	
	@Override
	public void orderNumberAdd(){
		Date nowDate = AboutTime.getYearMonthDay();
		int nowWeek = AboutTime.getWeek();
		Statistics statistics = statisticsMapper.selectByWeek(nowWeek);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowDateString = sdf.format(nowDate);
		String oldDateString = sdf.format( statistics.getTime() );
		if(oldDateString.equals(nowDateString)){
			int orderNumber = statistics.getOrderNumber();
			statistics.setOrderNumber(orderNumber+1);
		} else{
			statistics.setTime(nowDate);
			statistics.setOrderNumber(1);
		}
		statisticsMapper.update(statistics);
	}

	@Override
	public void setOrderNumberZero() {
		//首先获取今天的日期，获取星期
		Date nowDate = AboutTime.getYearMonthDay();
		int nowWeek = AboutTime.getWeek();
		//和数据库比较，如果数据库中没有，把日期置入进去，订单数量清零
		Statistics statistics = statisticsMapper.selectByWeek(nowWeek);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String nowDateString = sdf.format(nowDate);
		String oldDateString = sdf.format( statistics.getTime() );
		if(!oldDateString.equals(nowDateString)){
			statistics.setTime(nowDate);
			statistics.setOrderNumber(0);
			statisticsMapper.update(statistics);
		}
		
		Date decDate;
		int decWeek;
		Statistics statistics2;
		String oldDateString2;
		//然后 从(日期-1)(日期-6)都和数据库比较
		for(int i = 1 ; i<7 ; i++){
			decDate = AboutTime.nowDateDecreaseDay(i);
			String decDateString = sdf.format(decDate);
			//获取数据库中，该日对应的星期，应该是 (当前星期-i)+7%7
			decWeek = ( (nowWeek-i)+7 ) %7;
			if(decWeek == 0){
				decWeek = 7;
			}
			statistics2 = statisticsMapper.selectByWeek(decWeek);
			//System.out.println(statistics2);
			oldDateString2 = sdf.format( statistics2.getTime() );
			if(!oldDateString2.equals(decDateString)){
				statistics2.setTime(decDate);
				statistics2.setOrderNumber(0);
				statisticsMapper.update(statistics2);
			}
		}
	}
}
